<?php
declare (strict_types=1);

namespace app\login\controller;

use app\api\server\Token;
use think\Request;

class User
{
    /**
     * 小程序登录
     */
    public function login()
    {
        try {
            $code = \request()->get('code');

            $appid = 'wxb476f68c15de9b8b';
            $appSecret = "3794b3905faf84945361913fd8feb38d";

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
            //file_get_contents/curl
            $data = file_get_contents($url);
            $data = json_decode($data, true);

            if (!isset($data['openid'])) {
                abort(2001, "微信请求失败、请稍后重试");
            }

            # 判断当前openid是否在数据、如果存在（登录）、更新、不存在（注册）
            $is_user = \app\model\User::where("openid", '=', $data['openid'])->find();

            if (!$is_user) {
                // 没有注册、添加
                $res = \app\model\User::create(['openid' => $data['openid']]);
                $uid = $res->id;
            } else {
                # 注册、可以更新 session_key\
                $uid = $is_user->id;
            }

            $token = Token::createToken($uid);


            return json(['data' => ['token' => $token], 'msg' => 'ok', 'code' => 200]);
        } catch (\Exception $exception) {
            return json(['data' => [], 'code' => $exception->getCode(), 'msg' => $exception->getMessage()]);
        }

    }

    /**
     * 更新用户信息
     */
    public function updateUser()
    {
        try {
            $uid = \request()->uid;

            if (\request()->has('location')) {
                $location = \request()->post();
//                dd($location);
                $res =  \app\model\User::update(['city_id' => $location['ad_info']['city_code'],'id' => $uid]);

            } else {
                $nickname = \request()->post('nickname');
                $avatar = \request()->post('avatar');

                $res =  \app\model\User::update(['nickname' => $nickname,'avatar' => $avatar,'id' => $uid]);
            }
            $res = \app\model\User::find($uid);
            $data = [
                'userInfo' => [
                    'nickname' => $res->nickname,
                    'avatar' => $res->avatar
                ]
            ];

            return json(['data' => $data, 'msg' => 'ok', 'code' => 200]);
        } catch (\Exception $exception) {
            return json(['data' => [], 'code' => $exception->getCode(), 'msg' => $exception->getMessage()]);
        }
    }
}
